package com.tbit.utils;

import com.tbit.common.enums.HolidayTypeEnum;
import com.tbit.common.utils.SpringContextUtils;
import com.tbit.uqbike.object.pojo.Holiday;
import com.tbit.uqbike.service.base.RedisService;
import com.tbit.uqbike.webmanager.dao.core.HolidayDao;


import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * 节假日工具类
 *
 * 用于判断某天是否是节假日 ， 调休
 * @author <a href="mailto:zhang.zhiliang@tbit.com.cn">Zhang ZhiLiang</a>
 * @version 1.0
 * @see <a href="http://adsl1.tbit.com.cn:21490/pages/viewpage.action?pageId=82182491">订单号规范</a>
 * @since 2025/5/16
 */
public class HolidayUtils {

    private static final RedisService redisService = SpringContextUtils.getBean("redisService");
    private static final HolidayDao holidayDao = SpringContextUtils.getBean("holidayDao");

    /**
     * 判断传入的date日期是否节假日
     * @param date yyyy-MM-dd 日期字符串
     * @return true 为节假日 ， false 为节假日
     */
    public static boolean validHoliday(String date) {
        validData(getYear(date));
        return redisService.hasElementSet(HolidayTypeEnum.HOLIDAY.toString(), date);
    }

    /**
     * 判断传入的日期是否为调休
     * @param date yyyy-MM-dd 日期字符串
     * @return true 为节假日 ， false 为节假日
     */
    public static boolean validWorkOnWeekend(String date) {
        validData(getYear(date));
        return redisService.hasElementSet(HolidayTypeEnum.WORK_ON_WEEKEND.toString(), date);
    }

    /**
     * 获取年份
     * @param date yyyy-MM-dd 日期
     * @return yyyy 年份
     */
    private static String getYear(String date){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate = LocalDate.parse(date, formatter);
        return String.valueOf(localDate.getYear());
    }

    /**
     * 校验
     * 确保存在数据
     * @param year yyyy 年份
     */
    private static void validData(String year){
        if (!redisService.hasKey(HolidayTypeEnum.HOLIDAY.toString())){
            initHoliday(year);
        }
    }

    /**
     * 初始化一年的节假日到内存
     * @param year yyyy 年份
     */
    private static void initHoliday(String year){
        List<Holiday> holidayList = holidayDao.getByYear(year);
        LocalDateTime localDateTime = LocalDateTime.of(LocalDate.now().getYear(), 12, 31, 23, 59, 59, 999_000_000);
        Date endOfYear = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        redisService.addSet(HolidayTypeEnum.HOLIDAY.toString(), endOfYear, holidayList.stream().filter(Holiday::getHoliday).map(Holiday::getDate).toArray(String[]::new));
        redisService.addSet(HolidayTypeEnum.WORK_ON_WEEKEND.toString(),endOfYear, holidayList.stream().filter(x -> !x.getHoliday()).map(Holiday::getDate).toArray(String[]::new));
    }
}
